import React from 'react'
import {Row, Col, Button } from 'antd';
import MonthPicker from '../MonthPicker'
import './index.less'

export default class Pop extends React.PureComponent{
  constructor(props) {
    super(props);
    this.state = {
      range: props.range,
      isopen: false,
      mode: props.mode || 'year',
      popPositionLeft: true,
      value:  props.value || ''
    }
  }

  componentDidMount() {
    document.removeEventListener('click', this.func, false);
    document.addEventListener('click', this.func, false)
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.func, false)
  }
  // 设置不可以选择的日期
  isDisabled = (year) => {
    if (!this.state.value) {
      return this.state.range[1] && this.state.range[1] < year
    }
    return (this.state.range[1] && this.state.range[1] < year) ||
    (this.state.value[0] ? this.state.value[0] > year : false)
  }
  // 设置不可以选择的日期
  isDisabled2 = (year) => {
    if (!this.state.value) {
      return this.state.range[0] && this.state.range[0] > year
    }
    return (this.state.range[0] && this.state.range[0] > year) ||
    (this.state.value[1] ? this.state.value[1] < year : false);
  }
  // 关闭弹窗相关事件
  func = () => {
    this.props.closePop();
  }
  closePop = () => {
    this.props.closePop()
  }
  onYearChange1 = (val) => {
    this.setState({
      range: [val, this.state.range[1]]
    }, () => {
      this.props.setSelectedDate(val);
    })
  }
  onYearChange2 = (val) => {
    this.setState({
      range: [this.state.range[0], val]
    }, () => {
      this.props.setSelectedDate2(val);
    })
  }
  // 阻止冒泡
  preventDefaultOpen = (event) => {
    event.stopPropagation();
    event.nativeEvent.stopImmediatePropagation();
  }
  render() {
    const { popPositionLeft  } = this.props;
    return (<Row className="pop"
      onClick={this.preventDefaultOpen}
      style={{left: popPositionLeft? '0': 'auto',
        right:  popPositionLeft? 'auto': '0'}}
    >
      <Row>
        <Col span={8}><input readOnly
          value={this.state.range[0]}
        /></Col>
        <Col span={4}>~</Col>
        <Col span={8}><input readOnly
          value={this.state.range[1]}
        /></Col>
      </Row>
      <Row>
        <Col span={12}><MonthPicker disabledDate={this.isDisabled}
          onYearChange={this.onYearChange1.bind(this)}
          showYear={this.state.range[0]}></MonthPicker></Col>
        <Col span={12}><MonthPicker disabledDate={this.isDisabled2}
          onYearChange={this.onYearChange2.bind(this)}
          showYear={this.state.range[1]}></MonthPicker></Col>
      </Row>
      <Row style={{borderTop: '1px solid #ccc', lineHeight: '40px'}}>
        <Button onClick={this.closePop}
          size="small"
          style={{marginLeft: '10px'}}
        >确认</Button>
      </Row>
    </Row>
    )
  }
}